import React from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import TodoItem from './todoItem'
import {toggleTodo, removeTodo} from '../action'
import * as FilterTypes from '../../filter/filterTypes'
import {createSelector} from 'reselect'
const TodoList = ({todos, onToggleTodo, onRemoveTodo}) => {
  return (
    <ul className="todo-list">
      {
        todos.map(item => (
          <TodoItem 
            // 在一列子组件中，key值必须唯一。并且这个key值还需要是稳定不变的。一个常见的错误就是将元素在数组中的下标值作为key。
            key={item.id}
            text={item.text}
            completed={item.completed}
            onToggle={() => onToggleTodo(item.id)}
            onRemove={() => onRemoveTodo(item.id)}
          />
        ))
      }
    </ul>
  )
}
TodoList.propTypes = {
  todos: PropTypes.array.isRequired
}
const getFilter = state => state.filter
const getTodos = state => state.todos
const selectVisibleTodos = createSelector(
  [getFilter, getTodos],
    (filter, todos) => {
      switch (filter) {
        case FilterTypes.ALL:
          return todos;
        case FilterTypes.COMPLETED:
          return todos.filter(item => item.completed);
        case FilterTypes.UNCOMPLETED:
          return todos.filter(item => !item.completed);
        default:
          throw new Error('unsupported filter')
      }
  }
)

const mapStateToProps = state => {
  return {
    todos: selectVisibleTodos(state)
  }
}

const mapDispatchToProps = dispatch => {
  return {
    onToggleTodo: id => dispatch(toggleTodo(id)),
    onRemoveTodo: id => dispatch(removeTodo(id))
  }
}

// const mapDispatchToProps = (dispatch) => bindActionCreators({
//   onToggleTodo: toggleTodo,
//   onRemoveTodo: removeTodo
// }, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(TodoList)